#include "groupmodel.hpp"
#include "mysql.hpp"

using namespace std;
bool GroupModel::CreateGroup(Group& group) {
    char sql[1024] {0};
    sprintf(sql, "INSERT INTO allgroup (groupname, groupdesc) values ('%s', '%s');", 
    group.GetName().c_str(), group.GetDesc().c_str());
    // 防止重复插入
    MySql mysql;
    bool c = mysql.connect();
    if (!c) return false;
    c = mysql.update(sql);
    if (!c) return false;
    // 生成主键后
    const int id = mysql_insert_id(mysql.GetConection());
    group.SetId(id);
    return true;
}

void GroupModel::AddGroup(const int userId, const int groupId, std::string role) {
    char sql[1024] {0};
    sprintf(sql, "insert into groupuser values(%d, %d, '%s')", userId, groupId, role.c_str());
    MySql mysql;
    bool c = mysql.connect();
    if (!c) return;
    mysql.update(sql);
}

// 用于查询用户所在群组的相关信息
std::vector<Group> GroupModel::QueryGroupInfo(const int userId) {
    char sql[1024] {0};
    sprintf(sql, "SELECT g.id, g.groupname, g.groupdesc from allgroup g join groupuser gu on g.id = gu.groupid WHERE gu.userid = %d;", userId);
    MySql mysql;
    bool c = mysql.connect();
    if (!c) return {};
    std::vector<Group> groups;
    MYSQL_RES* res = mysql.query(sql);
    if (res == nullptr) return {};
    MYSQL_ROW row;
    while (row = mysql_fetch_row(res)) {
        Group group;
        group.SetId(stoi(row[0]));
        group.SetName(row[1]);
        group.SetDesc(row[2]);
        groups.push_back(group);
    }
    mysql_free_result(res);
    // 查询当前群聊里面所有的用户，追加到groupUser中
    // 我是知道当前群聊的id的，要把所有在这个群聊里面的用户都查出来
    for (Group& group : groups) {
        char sql2[1024] {0};
        sprintf(sql2, "select a.id, a.name, a.state, gu.grouprole from user a join groupuser gu on a.id = gu.userid where gu.groupid = %d;"
        , group.GetId());
        MYSQL_RES* res2 = mysql.query(sql2);
        if (res2 == nullptr) continue;
        MYSQL_ROW row2;
        while (row2 = mysql_fetch_row(res2)) {
            GroupUser gu;
            int id = atoi(row2[0]);
            std::string name = row2[1];
            string state = row2[2];
            std::string role = row2[3];
            gu.setId(id);
            gu.setName(name);
            gu.setState(state);
            gu.setRole(role);
            group.GetUsers().push_back(gu);
        }
        mysql_free_result(res2);
    }
    return groups;
}
// 用于服务器转发群消息 不能转发给自己
std::vector<int> GroupModel::QueryGroupUsers(const int userId, const int groupId) {
    char sql[1024] {0};
    sprintf(sql, "select userid from groupuser where groupid = %d and userid != %d;",
     groupId, userId);

    MySql mysql;
    bool c = mysql.connect();
    if (!c) return {};
    std::vector<int> users;
    MYSQL_RES* res = mysql.query(sql);
    if (res == nullptr) return {};
    MYSQL_ROW row;
    while (row = mysql_fetch_row(res)) {
        const int id = atoi(row[0]);
        users.push_back(id);
    }
    mysql_free_result(res);
    return users;
}
